package com.cloudfunx.common.util;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.redis.core.TimeoutUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author linjiayu
 */
public class LocalStoreCacheKit {

    private static final Map<String, Store> MAP = new ConcurrentHashMap<>();

    public static void set(String key, Object obj) {
        set(key, obj, -1);
    }

    /**
     * set store
     * @param key key
     * @param obj value
     * @param expires seconds
     */
    public static <T> void set(String key, T obj, final long expires) {
        MAP.put(key, new Store<T>(obj, key, expires * 1000, System.currentTimeMillis()));
    }

    public static <T> void set(String key, T obj, final long timeout, final TimeUnit unit) {
        MAP.put(key, new Store<T>(obj, key, TimeoutUtils.toMillis(timeout, unit), System.currentTimeMillis()));
    }

    public static <T> T get(String key) {
        Store store = MAP.get(key);
        if (Objects.nonNull(store)) {
            if (store.getExpires() == -1) {
                return (T) store.getObj();
            } else {
                if (store.getCurrent() + store.getExpires() >= System.currentTimeMillis()) {
                    return (T) store.getObj();

                } else {
                    //冗余删除
                    MAP.remove(key);
                }
            }
        }
        return null;
    }

    public static void remove(String key) {
        if (Objects.nonNull(get(key))) {
            MAP.remove(key);
        }
    }

    @Getter
    @Setter
    @AllArgsConstructor
    public static class Store<T> {
        private T obj;
        private String key;
        private long expires;
        private long current;

    }

}
